﻿using Furion;
using FurionApiDemo.Core.SignalRHub;
using FurionApiDemo.Util;
using FurionApiDemo.Web.Core.Filter;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;
using System;
using System.Text.Json;

namespace FurionApiDemo.Web.Core
{
    public class Startup : AppStartup
    {
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddJwt<JwtHandler>();

            services.AddCorsAccessor();

            services.AddControllers()
                    .AddInjectWithUnifyResult();

            // 添加即时通讯
            services.AddSignalR(options =>
            {
                // 客户端发保持连接请求到服务端最长间隔，默认30秒，改成4分钟，网页需跟着设置connection.keepAliveIntervalInMilliseconds = 24e4;即4分钟
                // options.ClientTimeoutInterval = TimeSpan.FromSeconds(5);
                // 服务端发保持连接请求到客户端间隔，默认15秒，改成2分钟，网页需跟着设置connection.serverTimeoutInMilliseconds = 12e4;即2分钟
                // options.KeepAliveInterval = TimeSpan.FromSeconds(5);
            });

            //定时任务/后台任务
            services.AddTaskScheduler();

            services.AddMvcFilter<RequestAuditFilter>();

            services.AddControllersWithViews()
            .AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.Converters.AddDateFormatString("yyyy-MM-dd HH:mm:ss");
            });
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseStaticFiles();

            // 注入httpcontext时用到
            GlobalContext.ServiceProvider = app.ApplicationServices;

            app.UseSerilogRequestLogging();

            app.UseRouting();

            app.UseCorsAccessor();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseInject(string.Empty);

            app.UseEndpoints(endpoints =>
            {
                // 注册集线器
                endpoints.MapHubs();
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");

                endpoints.MapControllers();
            });

            GlobalContext.LogWhenStart(env);
            GlobalContext.HostingEnvironment = env;
        }
    }
}